package oa.web.service;

import java.io.IOException;
import java.util.List;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import oa.core.*;
import oa.web.dao.impl.LoginDao;
import oa.web.dao.impl.SalaryDao;
import oa.web.pojo.Employee;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class SalaryService {
	
	@Autowired SalaryDao salaryDao;

    @Autowired
    private LoginDao<Employee> loginDao;

    @Autowired
    private LoginService loginService;


    @Autowired
    private MyRedis myRedis;

	public List<Employee> getByManagerId(int managerId){
		return salaryDao.getAllEmpoyeeByManagerId(managerId);
	}
	
	public double getCurrentUserOwnSalary(HttpServletRequest request){
        Employee emp = this.getCurrentUser(request);
        if(emp == null){
            return Constant.COOKIE_EXPIRE;
        }
        return emp.getSalary();
    }

    public List<Object> getCurrentManagerEmps(HttpServletRequest request){
        Employee employee = this.getCurrentUser(request);
        if(employee == null){
            return null;
        }
        return salaryDao.getAllEmpoyeeByManagerId(employee.getId());
    }

    public Employee getCurrentUser(HttpServletRequest request){
        Cookie loginCookie = MyCookie.getCookie(Constant.LOGIN_COOKIE_NAME, request);
        if(loginCookie!=null){
            String key = Constant.decodeBASE64(loginCookie.getValue());
            if(myRedis.existsKeyByte(key.getBytes())){
                try {
                    Employee emp = (Employee)MySerializable.unSerializable(myRedis.getObject(key.getBytes()));
                    return emp;
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return this.restoreAndReturnEmployee(key);
            }
        }
        return  null;
    }
    public Employee restoreAndReturnEmployee(String key){
        String token[] = Constant.decodeBASE64(key).split("_");
        String username = token[0];
        String md5_password = token[1];
        int status = loginService.isLogin(username,md5_password,Constant.COOKIE_LOGIN);
        if(status == Constant.LOGIN_STATUS_LOGIN_SUCCESS){
            try {
                Employee emp = (Employee)MySerializable.unSerializable(myRedis.getStr(key).getBytes());
                return emp;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
}
